<?php
/*
  导入信息
*/
namespace app\commands;

use Yii;
use yii\console\Controller;
use app\modules\Basic\models\CityCode;
use app\modules\Basic\models\HotelBrand;

class ImportController extends Controller
{

	//导入城市三字码
	public function actionCity(){//{{{
		$path = sprintf('%s/web/city.xlsx', Yii::$app->basePath);
		
        $datas = $this->getData($path);

        foreach($datas as $data){
	
			if($data['A']){
				$city_code = new CityCode();
				$city_code->code = $data['A'];
				$city_code->en_name = $data['B'];
				$city_code->zh_name = $data['C'];
		
				if($city_code->save()){
					echo "success ---".$city_code->id."----\n";
				}
        	}
        }
        
	
	}//}}}

    //导入品牌
    public function actionBrand(){

        $path = sprintf('%s/web/brand.xlsx', Yii::$app->basePath);
        
        $datas = $this->getData($path);

        foreach($datas as $data){
    
            if($data['B']){
                $hotel_brand = new HotelBrand();
                $hotel_brand->en_name = $data['B'];
                $hotel_brand->zh_name = $data['C'];
        
                if($hotel_brand->save()){
                    echo "success ---".$hotel_brand->id."----\n";
                }
            }
        }
    }
	//获取excel 数据
	private function getData($filePath){//{{{
		if(empty($filePath)){
			return [];
		}
		$PHPReader = new \PHPExcel_Reader_Excel2007();

		if(!$PHPReader->canRead($filePath)){
		    $PHPReader = new \PHPExcel_Reader_Excel5();
		}

		if(!$PHPReader->canRead($filePath)){
		    return ;
		}

		$PHPExcel = $PHPReader->load($filePath);

        $data = [];
     
	    $currentSheet = $PHPExcel->getSheet(0);

		/**取得最大的列号*/
	 	$allColumn = $currentSheet->getHighestColumn();

		/**取得一共有多少行*/
		$allRow = $currentSheet->getHighestRow();
					
		for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){

		    for($colIndex='A';$colIndex<='C';$colIndex++){
		        $addr = $colIndex.$rowIndex;
		        $cell = $currentSheet->getCell($addr)->getValue();
		        if($cell instanceof PHPExcel_RichText){     //富文本转换字符串
		            $cell = $cell->__toString();
				}
				if(!empty($cell)){
		        	$arrExcel[$rowIndex][$colIndex]= trim($cell);
				}else{
					$arrExcel[$rowIndex][$colIndex]= '';
				}
				$cell = '';
		    }

		}

        $data = $arrExcel;  
            
		return $data;

	}//}}}

 

  
}